initAcvicityLoation();

var locations = [];

// 初始化活动区域
function initAcvicityLoation() {
    $.ajax({
        url: root.promotion.search_activity_location,
        cache: false,  //禁用缓存
        type: "POST",
        // 告诉jQuery不要去处理发送的数据
        processData: false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType: false,
        data: {},
        async: true,
        success: function (data) {
            if (data != null && data.errorCode == 0) {
                locations = data.data;
                for (let i = 0; i < data.data.length; i++) {
                    const obj = data.data[i];
                    if(obj.warehouse_data_type !=2){
                        $("#activityLocation").append("<option value=" + obj.id + ">" + obj.warehouse_name + "</option>");
                    }

                }
            } else {
                layer.msg('活动区域初始化失败', {
                    icon: 2,
                    time: 3000
                });
            }
        },
        error: function () {
            console.log("!!!!活动区域初始化失败!!!!");
            layer.msg('活动区域初始化失败', {
                icon: 2,
                time: 3000
            });
        }
    });
}

// 表单提交
$(function () {
    $("#promotion_manage").validate({
        submitHandler: function (from) {
            $("#pageNum").val(1);
            $(from).ajaxSubmit({
                type: 'get',
                url: root.promotion.search_promotion_activity_by_page,
                success: function (data) {
                    console.log(data);
                    if (data.errorCode == 0) {
                        if (data.data.result.length > 0) {
                            initTabls(data.data.result);
                            power();
                            $('.M-box3').pagination({
                                pageCount: data.data.totalPage,
                                jump: true,
                                coping: true,
                                prevContent: '上页',
                                nextContent: '下页',
                                callback: function (api) {
                                    $("#pageNum").val(api.getCurrent());
                                    $(from).ajaxSubmit({
                                        type: 'get',
                                        url: root.promotion.search_promotion_activity_by_page,
                                        success: function (data) {
                                            if (data.errorCode == 0) {
                                                initTabls(data.data.result);
                                                power();
                                            } else {
                                                layer.msg(data.sub_msg, {
                                                    icon: 5,
                                                    time: 3000
                                                });
                                            }
                                        },
                                        error: function (XmlHttpRequest, textStatus, errorThrown) {
                                            console.log(XmlHttpRequest);
                                            console.log(textStatus);
                                            console.log(errorThrown);
                                            layer.msg('促销服务异常!', {
                                                icon: 5,
                                                time: 3000
                                            });
                                        }
                                    });
                                }
                            });
                        } else {
                            initTabls([]);
                        }
                    } else {
                        layer.msg(data.sub_msg, {
                            icon: 5,
                            time: 3000
                        });
                    }
                },
                error: function (XmlHttpRequest, textStatus, errorThrown) {
                    console.log(XmlHttpRequest);
                    console.log(textStatus);
                    console.log(errorThrown);
                    layer.msg('促销服务异常!', {
                        icon: 5,
                        time: 3000
                    });
                }
            });
        }
    });
});


// 渲染table
function initTabls(data) {
    if (data.length > 0) {
        $(".M-box3").show();
    } else {
        $(".M-box3").hide();
    }
    console.log(data);
    var dttable = $('#promotion_table').dataTable(); // 初始化dataTable，清空上一个值
    if (dttable) {
        dttable.fnDestroy(); //还原初始化了的datatable
        dttable.fnClearTable(); //清空一下table
    }
    addIndex(data);
    $("#promotion_table").DataTable({
        "autoWidth": false, // 自动宽度
        "ordering": false, // 开启排序
        "searching": false, //
        "paging": false,
        "serverSide": false, //启用服务器端分页
        "pagingType": "simple_numbers",
        "retrieve": true,
        "destroy": true,
        "bAutoWidth": false,
        "bLengthChange": false,
        "oLanguage": {
            "sLengthMenu": "每页显示 _MENU_ 条记录",
            "sZeroRecords": "抱歉， 没有找到",
            "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
            "sInfoEmpty": "没有数据",
            "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "前一页",
                "sNext": "后一页",
                "sLast": "尾页"
            },
            "sZeroRecords": "没有检索到数据",
            "sProcessing": "<img src='../../static/h-ui.admin/images/loading.gif' />",
        },
        "data": data,
        "columns": [{
            "data": "index"
        },
            {
                "data": "activityType",
                render: function (data, type, row) {
                    return data == 10 ? '单品促销' : '满减促销';
                }
            },
            {
                "data": "activityName",
                "type": "string"
            },
            {
                "data": "startTime",
                "type": "string",
                render: function (data, type, row) {
                    var end = row.endTime == "" ? "不限" : row.endTime
                    console.log(end);
                    return data + '~' + end;
                }
            },
            {
                "data": "activityLocation",
                "type": "string",
                render: function (data, type, row) {
                    return selectLocationName(data) == "" ? data : selectLocationName(data);
                }
            },
            {
                "data": "activityPerson",
                "type": "string",
                render: function (data, type, row) {
                    switch (data) {
                        case 10:
                            return '普通客户';
                            break;
                        case 20:
                            return '签约客户(非分销)';
                            break;
                        case 30:
                            return '签约客户(分销)';
                            break;
                        default:
                            return '未定义';
                            break;
                    }
                }
            },
            {
                "data": "activityStatus",
                render: function (data, type, row) {
                    switch (data) {
                        case 10:
                            return "已取消"
                        case 20:
                            return '未开始';
                            break;
                        case 30:
                            return '进行中';
                            break;
                        case 40:
                            return '已结束';
                            break;
                        default:
                            return '未定义';
                            break;
                    }
                }
            },
            {
                "data": "createdAt",
                "type": "string"
            },
            {
                "data": "createUsername",
                "type": "string"
            },
            {
                "data": "activityId",
                "type": "string",
                "render": function (data, type, row) {
                    var copyBtn = '<a href="javascript:void(0)" class="powerButton 450" onclick="editActivity(' + row.activityId + ',' + row.activityType + ',\'copy\')" class="ml-10">复制</a>'
                    var canCancel = '';
                    if (row.activityStatus == 20) {  // 只有未开始可以取消
                        canCancel = '<a href="javascript:void(0)" class="powerButton 451" onclick="cancelActivity(' + row.activityId + ')" class="ml-10">&nbsp;取消</a>';
                    }
                    /*2020-12需求已取消，已结束的促销支持修改*/
                    var canedit = '<a href="javascript:void(0)" class="powerButton 450" onclick="editActivity(' + row.activityId + ',' + row.activityType + ',\'edit\')" class="ml-10">&nbsp;修改</a>';
                    return copyBtn+'<a href="javascript:void(0)" class="powerButton 449"  onclick="seeActivity(' + row.activityId + ',' + row.activityType + ',\' 查看活动详情\',\'promotion_see.html\')" class="ml-10">&nbsp;查看</a>' +
                        canedit + canCancel;
                }
            }
        ]
    });

}

// 添加行号
function addIndex(data) {
    if (data.length > 0) {
        var pageNum = $("#pageNum").val();
        var start = (pageNum - 1) * 50;
        for (let i = 0; i < data.length; i++) {
            const datum = data[i];
            datum.index = i + start + 1;
        }
    }
}

var seeActivityId = 0;
var seeActivityType = 0;

// 查看活动详情
function seeActivity(activityId, activityType, title, html) {
    seeActivityId = activityId;
    seeActivityType = activityType;
    var index = layer.open({
        type: 2,
        title: title,
        content: html
    });
    layer.full(index);
}

var activityId = 0;
var activityType = 0

// 编辑活动
function editActivity(id, type, editType, html) {
    activityId = id;
    activityType = type;
    if(editType=="edit"){
        if (type == 10) {
            /*单品促销*/
            var index = layer.open({
                type: 2,
                title: '更改单品促销',
                content: 'singlepro_detail.html'
            });
            layer.full(index);
        } else {
            /*满减促销*/
            var index = layer.open({
                type: 2,
                title: '更改满减促销',
                content: 'reductionpro_detail.html'
            });
            layer.full(index);
        }
    }else {
        if (type == 10) {
            /*单品促销*/
            var index = layer.open({
                type: 2,
                title: '复制单品促销',
                content: 'copy_singlepro_detail.html'
            });
            layer.full(index);
        } else {
            /*满减促销*/
            var index = layer.open({
                type: 2,
                title: '复制满减促销',
                content: 'copy_reductionpro_detail.html'
            });
            layer.full(index);
        }
    }

}

// 取消活动
function cancelActivity(activityId) {
    $.ajax({
        url: root.promotion.cancel_activity_by_id,
        cache: false, //禁用缓存
        contentType: 'application/x-www-form-urlencoded',
        type: "PUT",
        data: {"activityId": activityId, "activityStatus": 10},
        success: function (data) {
            if (data.errorCode == 0) {
                layer.msg('取消成功', {
                    icon: 1,
                    time: 3000
                });
                $("#promotion_manage").submit();
            } else {
                layer.msg(data.sub_msg, {
                    icon: 2,
                    time: 3000
                });
            }
        },
        error: function () {
            console.log("!!!!取消失败,促销后台异常!!!!");
            layer.msg('取消失败,促销后台异常', {
                icon: 2,
                time: 3000
            });
        }
    });
}

// 获取活动区域
function selectLocationName(id) {
    if (locations.length > 0) {
        for (let i = 0; i < locations.length; i++) {
            const lo = locations[i];
            if (id == lo.id) {
                return lo.warehouse_name;
            }
        }
    }
    return "";
}

function reloadTable() {
    $("#form_subbmit").submit();
}
